<template>
  <div>
    <zm-panel title="选择产品" :visible.sync="value" @change="close" class="selectProductStyle">
      <app-block>
        <div class="df-wrap df">
          <div class="w200 br mr20">
            <el-tree :data="treeList" :props="defaultProps" :default-expand-all="true" :expand-on-click-node="true" :check-on-click-node="true" current-node-key="-1" node-key="id" highlight-current @node-click="handleNodeClick" class="treeStyle" v-loading="loading"></el-tree>
          </div>
          <div class="flex1">
            <zm-form :model="searchForm" ref="searchForm" inline class="mt20">
              <zm-form-item>
                <zm-input v-model="searchForm.productName" placeholder="请输入产品名称/编码查询" class="w200"></zm-input>
              </zm-form-item>
              <zm-form-item>
                <zm-input class="w200" v-model="searchForm.minVal" placeholder="最小值">
                  <span slot="append">元</span>
                </zm-input>
                <zm-data-select class="w100" v-model="searchForm.minOperator" :list="pareList" placeholder="请选择"></zm-data-select>
              </zm-form-item>
              <!-- <span class="physical-product-config__text">最低销售单价</span> -->
              <zm-form-item label="最低销售单价"></zm-form-item>
              <zm-form-item>
                <zm-data-select class="w100" v-model="searchForm.maxOperator" :list="pareList" placeholder="请选择"></zm-data-select>
                <zm-input class="w200" v-model="searchForm.maxVal" placeholder="最大值">
                  <span slot="append">元</span>
                </zm-input>
              </zm-form-item>
              <zm-form-item>
                <zm-button type="primary" @click="toSearch">查询</zm-button>
                <zm-button type="warning" @click="toReset" t="reset"></zm-button>
              </zm-form-item>
              <zm-form :model="form" ref="zmForm" :rules="productRules">
                <zm-form-item prop="">
                  <span> 已选择数量：（{{ selectedList.length || 0 }}） </span>
                </zm-form-item>
              </zm-form>
            </zm-form>
            <zm-table-data :data="tableParams.data" ref="multipleTable" pk="id" :columns="columns" :fetch="loadList" :table-params="tableParams" :mutilple="true" :checked="selectedIds" v-loading="loading" @selection-change="saveIds"></zm-table-data>
            <!-- @selection-change="saveIds" -->
          </div>
        </div>
      </app-block>
      <div slot="footer" class="tr">
        <zm-button @click="close" type="">返回</zm-button>
        <zm-button @click="submit" type="primary">确定</zm-button>
      </div>
      <detail-container v-if="productVisible" v-model="productVisible" :id="detailProductId" :obj="detailProductObj" :is-form-sale="isFormSale"></detail-container>
    </zm-panel>
  </div>
</template>
<script>
import panelMixin from '@/mixins/panelMixin'
import tableMixin from '@/mixins/zmTableMixin'
// import productApis from '@/api/src/product'
import productDraftApis from '@/api/src/productDraft'
import publicApis from '@/api/src/public'
import DetailContainer from '../../../physicalProductConfigDetail/index.vue'

import { shiwuProductColumns } from './const'
export default {
  components: { DetailContainer },
  mixins: [panelMixin, tableMixin],
  props: {
    productInfo: {
      type: [Object, Array],
      default () {
        return {}
      }
    },
    isMulti: {
      type: String,
      default: '-1'
    },
    isOnSaleOrder: {
      type: String,
      default: ''
    },
    isFormSale: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      columns: shiwuProductColumns(this),
      loading: false,
      pareList: [ // 最值选项
        {
          value: 'lt',
          name: '<'
        },
        {
          value: 'elt',
          name: '<='
        }
      ],
      form: {

      },
      searchForm: {
        categoryId: '', // 一级或二级分类id
        isMulti: '-1', // 是否组合(-1全部 0否 1是)
        productName: '', // 商品名称或编码
        minVal: '', // 最低销售单价最小值
        minOperator: '', // 最低销售单价最小值比对运算符 (<, <=)
        maxVal: '', // 最低销售单价最大值
        maxOperator: '' // 最低销售单价最大值比对运算符 (<, <=)
      },
      productVisible: false,
      detailProductId: '',
      detailProductObj: {},
      productRules: {
        productId: [
          {
            required: 'true',
            message: '请选择一个产品',
            trigger: 'change'
          }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      treeList: [],
      selectedList: [],
      selectedIds: [] // 回传的id数组
    }
  },
  computed: {},
  watch: {},
  created () {
    // console.log(this.productInfo, 'this.productInfo')
    this.getTree()

    this.selectedList = JSON.parse(JSON.stringify(this.productInfo))

    this.selectedIds = this.selectedList.length ? this.selectedList.map(item => item.id) : []
  },
  methods: {
    async loadList () {
      this.loading = true
      const _res = await productDraftApis.getProductList(
        this.assignQuery({
          ...this.searchForm,
          isMulti: this.isMulti,
          status: '1',
          isOnSaleOrder: this.isOnSaleOrder //  isOnSaleOrder = 1 过滤账号销售部门数据
        })
      )

      const idsArr = this.selectedList.length ? this.selectedList.map(item => item.id) : []
      const _list =
        this.isMultiple &&
        _res.list.map(item => {
          return {
            ...item,
            isChecked: idsArr.includes(item.id)
          }
        })
      this.loading = false
      this.initialTableData(this.isMultiple ? _list : _res.list, _res.count)
    },
    toSearch() {
      this.$set(this.tableParams, 'page', 1)
      this.loadList && this.loadList()
    },
    toReset () {
      this.$set(this, 'searchForm', {
        productName: '', // 商品名称或编码
        minVal: '', // 最低销售单价最小值
        minOperator: '', // 最低销售单价最小值比对运算符 (<, <=)
        maxVal: '', // 最低销售单价最大值
        maxOperator: '' // 最低销售单价最大值比对运算符 (<, <=)
      })
      this.toSearch()
    },
    async getTree () {
      const _res = await publicApis.getProductCategoryList()
      let childArr = _res
      let allArr = [
        {
          name: '全部',
          id: '-1'
        },
        ...childArr
      ]
      this.treeList = allArr
    },
    handleNodeClick (node) {
      if (!node.children || node.children.length === 0) {
        this.searchForm.categoryId = node.id
        this.onSearch()
      }
    },
    // 操作按钮
    onDetail (row) {
      // 调用产品详情
      // 调用产品详情
      this.detailProductObj = row
      this.detailProductId = row.id
      this.productVisible = true
    },
    chooseRadio (row) {
      this.form = {
        ...this.form,
        ...row,
        productId: row.id
      }
    },
    handleSelect (selection, row) {
      const ids = this.selectedList.map(i => i.id)
      if (!ids.includes(row.id)) {
        this.selectedList.push(row)
      } else {
        this.selectedList = this.selectedList.filter(i => i.id !== row.id)
      }
    },
    saveIds (selection, row) {
      // 保存已选
      this.selectedNos = selection.map(item => item.id).join(',')
      this.selectedList = selection
    },
    submit () {
      let _valid = false
      this.$refs.zmForm.validate(valid => {
        _valid = valid
      })
      if (!_valid) return

      if (this.isMultiple && this.selectedList.length === 0) {
        this.$message.error('请选择产品')
        return
      }
      this.$emit('after-select', this.selectedList)
      this.close()
    }
  }
}
</script>
<style lang="scss">
.selectProductStyle {
  .treeStyle {
    .el-tree-node__label {
      font-weight: 600 !important;
    }
    .el-tree-node__children {
      .el-tree-node__label {
        font-weight: 400 !important;
      }
    }
  }
}
</style>
